# Used to grab images from an IP2031 embedded webcam server. iCamserver? compatible
# Nigel Sim <nigel.sim@gmail.com>

from socket import *

class IP2031:
    def connect(self, video_no=1):
        """
        0,1 - session id
        2,3,4,5 - 4321
        6,7 - video_no
        """
        buf = `self.sid`+'43210'+`video_no`
        #print buf
        self.send(buf)
        d, src = self.p.recvfrom(2000)
        if int(d[0:2]) != self.sid:
            print "error"

    def getInfo(self):
        """
        0,1 - session id
        2,3,4,5 - 5102
        """
        buf = `self.sid`+'5102'
        #print buf
        self.send(buf)
        d, src = self.p.recvfrom(2000)
        if int(d[0:2]) != self.sid:
            print "error"

    def disconnect(self):
        """
        0,1 - session id
        2,3,4,5 - 0011
        """
        buf = `self.sid`+'0011'
        self.send(buf)

    def getImage(self):
        """
        0,1 - session id
        2-7 - offset (always zero for first image)
        8-15 - image size (bytes)
        16-24 - date/time in some hex format
        """
        buf = `self.sid`+'3002'
        self.send(buf)
        d, src = self.p.recvfrom(2000)

        sect = int(d[0:2])
        if int(d[0:2]) != self.sid:
            print "error"
            return
        offset = int(d[2:8])
        size = int(d[8:16])
        date = d[16:24]
        #print offset, size, date

        img = d[25:]
        while len(img) < size:
            d, src = self.p.recvfrom(2000)
            img = img + d[8:]
        return img # return image buffer (jpeg)

    def send(self, buf):
        self.p.sendto(buf, self.addr)

    def __init__(self, address, port):
        self.p = socket(AF_INET,SOCK_DGRAM)
        self.addr = (address, port)
        self.sid = 15


if __name__ == '__main__':
    import sys

    if len(sys.argv) == 4:
        x = IP2031(sys.argv[1], int(sys.argv[2]))
        x.disconnect() #seems to ensure we can reconnect 
        print "Connect"
        x.connect()
        print "Getting Image"
        f = open(sys.argv[3],'w')
        f.write(x.getImage())
        f.close()
        x.disconnect()
    else:
        print "Arguments: <address> <port> <output file>"
